package com.vcaresolution.logistic.util;

import java.beans.PropertyEditorSupport;

import org.springframework.util.StringUtils;

import com.vcaresolution.util.Utils;

public class CustomIntegerEditor extends PropertyEditorSupport {

	private final boolean allowEmpty;

	/**
	 * Create a new CustomTimestampEditor instance, using the given DateFormat
	 * for parsing and rendering.
	 * <p>
	 * The "allowEmpty" parameter states if an empty String should be allowed
	 * for parsing, i.e. get interpreted as null value. Otherwise, an
	 * IllegalArgumentException gets thrown in that case.
	 *
	 * @param dateFormat
	 *            DateFormat to use for parsing and rendering
	 * @param allowEmpty
	 *            if empty strings should be allowed
	 */
	public CustomIntegerEditor(final boolean allowEmpty) {
		this.allowEmpty = allowEmpty;
	}

	/**
	 * Parse the Date from the given text, using the specified DateFormat.
	 */
	@Override
	public void setAsText(final String text) throws IllegalArgumentException {
		if (allowEmpty && !StringUtils.hasText(text)) {
			// Treat empty String as null value.
			setValue(null);
		} else {
			final boolean isValidDigit = Utils.isValidDigit(text);

			if (!isValidDigit) {
				throw new IllegalArgumentException("Could not parse digit: ");
			} else {
				final Integer parsedInteger = Integer.parseInt(text);
				setValue(parsedInteger);
			}
		}
	}

	/**
	 * Format the Integer as String.
	 */
	@Override
	public String getAsText() {
		final Integer digit = (Integer) getValue();
		String number = null;
		if (digit != null) {
			number = String.valueOf(digit);
		}
		return number;
	}

}
